package com.hou.eduservice.controller.front;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hou.commonutils.JwtUtils;
import com.hou.commonutils.R;
import com.hou.commonutils.ordervo.CourseWebVoOrder;
import com.hou.eduservice.client.OrdersClient;
import com.hou.eduservice.entity.EduCourse;
import com.hou.eduservice.entity.chapter.ChapterVo;
import com.hou.eduservice.entity.frontvo.CourseFrontVo;
import com.hou.eduservice.entity.frontvo.CourseWebVo;
import com.hou.eduservice.service.EduChapterService;
import com.hou.eduservice.service.EduCourseService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.OrderComparator;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @author shkstart
 * @create 2021-11-28-9:08
 */
@CrossOrigin
@RestController
@RequestMapping("/eduservice/coursefront")
public class CourseFrontController {

    @Autowired
    private EduCourseService eduCourseService;

    @Autowired
    private EduChapterService eduChapterService;

    @Autowired
    private OrdersClient ordersClient;

    // 带分页条件查询课程
    @PostMapping("getCourseLimit/{page}/{limit}")
    public R getCourseLimit(@PathVariable Long page, @PathVariable Long limit,
                            @RequestBody (required = false) CourseFrontVo course) {

        Page<EduCourse> pageLimit = new Page<>(page, limit);

        Map <String,Object> map = eduCourseService.getCourseLimit(pageLimit,course);

        return R.ok().data(map);

    }

    // 课程详情
    @GetMapping("getFrontCourseInfo/{courseId}")
    public R getFrontCourseInfo(@PathVariable String courseId, HttpServletRequest request) {

        // 获取课程信息
        CourseWebVo courseWebVo = eduCourseService.getBaseCourseInfo(courseId);

        // 根据id查询章节和小节
        List<ChapterVo> chapterVideoList = eduChapterService.getChapterVideoById(courseId);

        // 根据课程id和用户id查询当前课程是否被购买
        String memberIdByJwtToken = JwtUtils.getMemberIdByJwtToken(request);
        Boolean aBoolean = ordersClient.courseIsBuy(memberIdByJwtToken, courseId);


        return R.ok().data("courseWebVo",courseWebVo).data("chapterVideoList",chapterVideoList).data("isBuy",aBoolean);

    }

    // 根据课程id查询课程信息
    @PostMapping("getCourseInfoOrder/{id}")
    public CourseWebVoOrder getCourseInfoOrder (@PathVariable String id){
        CourseWebVo courseInfo = eduCourseService.getBaseCourseInfo(id);
        CourseWebVoOrder courseWebVoOrder = new CourseWebVoOrder();
        BeanUtils.copyProperties(courseInfo,courseWebVoOrder);
        return courseWebVoOrder;
    }

}
